package com.swf.common.data;

import com.swf.common.base.*;
import com.swf.common.utils.*;

/**
 * description:基本数据项元素定义
 * @version 1.0 2013-5-14
 * @author shenwf
 */
public class FwsDataField extends FwsDataElement{
	/**
	 * 数据项的值
	 */
	private Object value;
	/**
	 * 数据的初始值
	 */
	private Object defaultValue;
	/**
	 * 数据描述
	 */
	private String description; 
	/**
	 * 数据类型索引
	 */
	private String dataType;
	/**
	 * 是否为必须域
	 */
	private boolean required = false;
	public FwsDataField() {
	}
	public FwsDataField(String name) {
		super(name);
	}
	public FwsDataField(String name,Object value) {
		super(name);
		setValue(value);
	}
	
	
	
	public Object getValue() {
		return value;
	}
	public void setValue(Object value) {
		this.value = value;
	}
	public Object getDefaultValue() {
		return defaultValue;
	}
	public void setDefaultValue(Object defaultValue) {
		this.defaultValue = defaultValue;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getDataType() {
		return dataType;
	}
	public void setDataType(String dataType) {
		this.dataType = dataType;
	}
	public boolean isRequired() {
		return required;
	}
	public void setRequired(boolean required) {
		this.required = required;
	}

	@Override
	public Object clone() {
		FwsDataField field = new FwsDataField();
		field.setName(getName());
		field.setValue(value);
		field.setDefaultValue(defaultValue);
		field.setDataType(dataType);
		field.setAppend(isAppend());
		return field;
	}
	@Override
	public String toString() {
		return toString(0);
	}
	
	@Override
	public String toString(int tabCount) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < tabCount; i++)
			buf.append("\t");
		buf.append("<field id=\"");
		buf.append(getName());
		String passString =  FwsStandard.getBasicSettingsValue("PasswordField.Masked");
		String[] passKey = passString.split(","); 
		if (value != null){
			String  tempValue = value.toString();
			if (FwsStringUtils.contains(passKey, getName())){
				tempValue = "******";
			}
			buf.append("\" value=\"");
			buf.append(formatXML(tempValue));
		}
		if (dataType!=null){
			buf.append("\" dataType=\"");
			buf.append(dataType);
		}
		buf.append("\" append=\""+isAppend()+"\"/>");
		return buf.toString();
	}
	
	/**
	 * 将数据中的特殊字符进行转换，使得作为XML中的内容时能正确显示
	 * @param input 字符串
	 * @return 处理后的字符串
	 */
	private String formatXML(String input){
		return FwsStringUtils.isBlank(input)?input:FwsStringEscapeUtils.escapeXml(input);
	}
	
	/**
	 * 生成JSON串，java和js区别只有'和 /
	 * @return
	 */
	public String toJson(){
		StringBuffer buf = new StringBuffer();
		if (value!=null){
			String temp = value.toString();
			temp = FwsStringEscapeUtils.escapeJavaScript(temp);
			buf.append("\""+temp+"\"");
		}else{
			buf.append("null");
		}
		return buf.toString();
	}
	
}
